package com.qf.controller;

import com.qf.utils.CodeUtils;
import com.qf.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendcode")
    public HashMap<String,Object> sendcode(String phone){

        // 记录该接口被访问了一次
        // 该接口的访问次数，存放到 redis 中的hash结构中
        // key = api:counts , 对内部的field = /login/sendcode 进行加1


        //1. 生成一个6位数的验证码
        String code = CodeUtils.createCode(6);

        //2. 保存验证码到redis中
        String key = "login:sendcode:"+phone;
        redisTemplate.opsForValue()
                .set(key,code,5, TimeUnit.MINUTES);

        //3. 调用阿里云的短信接口发送短信给指定手机
        System.out.println(code);
        //4. 返回json
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code",1);
        hashMap.put("msg","ok");

        return hashMap;

    }


    @PostMapping("/login")
    public HashMap<String,Object> login(String phone,String code){

        //1. 根据phone去redis中查询 验证码
        String key = "login:sendcode:"+phone;
        String redisCode = (String) redisTemplate.opsForValue()
                .get(key);

        //2. 比对验证码
        if (redisCode==null){
            // 验证码过期了
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("code",-1);
            hashMap.put("msg","验证码过期了或者手机号输入错误");
            return hashMap;
        }

        if (redisCode.equals(code)){
            // 验证码正确 登录成功
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("code",1);
            hashMap.put("msg","ok");

            // 颁发jwt
            String token = JwtUtils.createToken(phone, 120);

            hashMap.put("data",token);

            return hashMap;
        }else {
            // 验证码错误 登录失败
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("code",-1);
            hashMap.put("msg","验证码错误");
            return hashMap;
        }

    }


}
